package com.demo.web;

import com.demo.service.StudentService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            //获取前台的参数 num
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            //调用service的check方法得到一个boolean值
            boolean flag = new StudentService().login(username, password);
            HttpSession session = req.getSession();


            //4.创建一个Map对象,给map中设置内容
            Map<String, Object> map = new HashMap<String, Object>();

            if (flag) {
                session.setAttribute("userKey_session", username);
                map.put("isLogin", true);
                map.put("msg", "登录成功");
            } else {
                map.put("isLogin", false);
                map.put("msg", "登录失败");
            }
            //map转成json返回给前台.
            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(map);

            //json数据返回给前台
            resp.getWriter().println(mapJson);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
